package c.a.md.androidvideo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

public class PKGDecodeActivity extends AppCompatActivity
{
    View btn1;

    private MediaExtractor mediaExtractor;
    private MediaMuxer mediaMuxer;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pkgdecode);

        btn1 = findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                doWork();
            }
        });
    }

    private void doWork()
    {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE}, 9);
        } else
        {
            process();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 9)
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                process();
            }
        }
    }

    private void process()
    {
        new Thread()
        {
            @Override
            public void run()
            {
                doNext();
            }
        }.start();
    }

    private boolean doNext()
    {
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Video/V81022-114324.mp4");
        if(f.exists())
        {
            mediaExtractor = new MediaExtractor();
            try
            {
                mediaExtractor.setDataSource(f.getAbsolutePath());
                int numTrack = mediaExtractor.getTrackCount();
                int frameRate = 0;
                int mVideoTrackIndex = -1;
                for (int i = 0; i < numTrack; i++)
                {
                    MediaFormat format = mediaExtractor.getTrackFormat(i);
                    String mime = format.getString(MediaFormat.KEY_MIME);
                    if(!mime.startsWith("video/"))
                    {
                        continue;
                    }
                    frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
                    mediaExtractor.selectTrack(i);
                    mediaMuxer = new MediaMuxer(Environment.getExternalStorageDirectory().getAbsolutePath() + "/asd.mp4",
                            MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
                    mVideoTrackIndex = mediaMuxer.addTrack(format);
                    mediaMuxer.start();
                }

                if(mediaMuxer == null)
                {
                    return false;
                }

                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                info.presentationTimeUs = 0;
                ByteBuffer buffer = ByteBuffer.allocate(500 * 1024);
                int sampleSize = 0;
                while((sampleSize = mediaExtractor.readSampleData(buffer, 0)) > 0)
                {
                    info.offset = 0;
                    info.size = sampleSize;
                    info.flags = MediaCodec.BUFFER_FLAG_KEY_FRAME;
                    info.presentationTimeUs += 1000 * 1000 / frameRate;
                    mediaMuxer.writeSampleData(mVideoTrackIndex, buffer, info);
                    mediaExtractor.advance();
                }

                mediaExtractor.release();
                mediaMuxer.stop();
                mediaMuxer.release();
                return true;
            } catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}
